"use strict"

import { app, BrowserWindow, Menu, ipcMain } from "electron"

import * as express from "express"
import * as expressWebSocket from "express-ws"
import webSocketStream from "websocket-stream/stream"
import ffmpegPath from '@ffmpeg-installer/ffmpeg'
import ffprobePath from '@ffprobe-installer/ffprobe'
import ffmpeg from "fluent-ffmpeg"

/**
 * Set `__static` path to static files in production
 * https://simulatedgreg.gitbooks.io/electron-vue/content/en/using-static-assets.html
 */
if (process.env.NODE_ENV !== "development") {
  // 修复 electron asar 不能使用二进制文件的问题
  ffmpegPath.path = ffmpegPath.path.replace('app.asar', 'app.asar.unpacked')
  ffprobePath.path = ffprobePath.path.replace('app.asar', 'app.asar.unpacked')

  global.__static = require("path")
    .join(__dirname, "/static")
    .replace(/\\/g, "\\\\")
}

app.allowRendererProcessReuse = true
// ffmpeg
ffmpeg.setFfmpegPath(ffmpegPath.path)
ffmpeg.setFfprobePath(ffprobePath.path)
app.on("ready", localServer)
function localServer() {
  let app = express()
  app.use(express.static(__dirname))
  expressWebSocket(app, null, {
    perMessageDeflate: true
  })
  app.ws("/rtsp/:id/", rtspRequestHandle)
  app.listen(8888)
  console.log("express listened")
}

function rtspRequestHandle(ws, req) {
  console.log("rtsp request handle")
  const stream = webSocketStream(ws, {
    binary: true,
    browserBufferTimeout: 1000000
  }, {
    browserBufferTimeout: 1000000
  })
  let url = req.query.url
  console.log("rtsp url:", url)
  console.log("rtsp params:", req.params)
  try {
    ffmpeg(url)
      .addInputOption("-rtsp_transport", "tcp", "-buffer_size", "102400")  // 这里可以添加一些 RTSP 优化的参数
      .on("start", function () {
        console.log(url, "Stream started.")
      })
      .on("codecData", function () {
        console.log(url, "Stream codecData.")
        // 摄像机在线处理
      })
      .on("error", function (err) {
        console.log(url, "An error occured: ", err.message)
      })
      .on("end", function () {
        console.log(url, "Stream end!")
        // 摄像机断线的处理
      })
      .outputFormat("flv").videoCodec("copy").noAudio().pipe(stream)
  } catch (error) {
    console.log(error)
  }
}

// 关闭顶部菜单栏
Menu.setApplicationMenu(null)

let mainWindow
const winURL =
  process.env.NODE_ENV === "development"
    ? `http://localhost:9080`
    : `file://${__dirname}/index.html`

function createWindow() {
  /**
   * Initial window options
   */
  mainWindow = new BrowserWindow({
    frame: false, // 关闭顶部标题栏
    height: 711, // 缩小时默认高度
    useContentSize: true,
    width: 1266, // 缩小时默认宽度
    minWidth: 1266,
    minHeight: 711,
    webPreferences: {
      webSecurity: false,
      nodeIntegration: true,
    },
  })
  mainWindow.maximize()
  mainWindow.loadURL(winURL)

  mainWindow.on("closed", () => {
    mainWindow = null
  })
}



app.on("ready", createWindow)

app.on("window-all-closed", () => {
  if (process.platform !== "darwin") {
    app.quit()
  }
})

app.on("activate", () => {
  if (mainWindow === null) {
    createWindow()
  }
})

ipcMain.on("min", (e) => mainWindow.minimize())
ipcMain.on("max", (e) => {
  if (mainWindow.isMaximized()) {
    mainWindow.unmaximize()
  } else {
    mainWindow.maximize()
  }
})
// 执行关闭 自定义关闭
ipcMain.on("handelClose", function (res) {
  console.log("执行关闭操作")
  app.quit()
})

/**
 * Auto Updater
 *
 * Uncomment the following code below and install `electron-updater` to
 * support auto updating. Code Signing with a valid certificate is required.
 * https://simulatedgreg.gitbooks.io/electron-vue/content/en/using-electron-builder.html#auto-updating
 */

/*
import { autoUpdater } from 'electron-updater'

autoUpdater.on('update-downloaded', () => {
  autoUpdater.quitAndInstall()
})

app.on('ready', () => {
  if (process.env.NODE_ENV === 'production') autoUpdater.checkForUpdates()
})
 */
